import { useCallback, useEffect, useState } from "react";
import { message } from "antd";
import request from "@/utils/request";
import { stringify } from "qs";

import { usePolling } from "@/views/hooks/usePolling";

/**
 * 创建导入任务
 * @param {*} businessParam   "{ businessKey: '1', query:{  storeId: xx  } }"
 * @param {*} businessParam   "{ businessKey: '2',query:{  搜索条件  }  }"
 * @param {*} businessParam   "{ businessKey: '3',query:{  ids:[x,x,x,x]  } }"
 * @param {*} taskType
 * @returns
 */
async function createImportTask(params) {
	return request(`/blade-log/taskInfo/createImportTask`, {
		method: "POST",
		data: params,
		loading: true
	});
}

/**
 * 获取导入任务进度
 * @param {*} params taskId
 * @returns  completed  importedNum  taskId  totalNum
 */
async function getImportTaskRate(params) {
	return request(`/blade-log/taskInfo/getImportTaskRate?${stringify(params)}`, {
		loading: false
	});
}

/**
 * 下载⽂件
 * @param {*} params id
 * @returns
 */
async function downLoadFile(params) {
	return request(`/blade-log/taskInfo/downLoadFile?${stringify(params)}`, {
		method: "GET",
		// getResponse: true,
		// responseType: "blob",
		loading: true
	});
}
export const useImportTask = () => {
	const [step, setStep] = useState({
		first: null,
		second: null,
		third: null
	});
	const [taskId, setTaskId] = useState("");
	const [percent, setPercent] = useState(0);
	const [result, setResult] = useState({
		taskId: null,
		totalNum: null,
		importedNum: null,
		successNum: null,
		failNum: null,
		completed: null,
		interrupted: null,
		message: null
	});

	const { setTimer, clearTimer } = usePolling();

	const handleDownload = useCallback(
		_id => {
			const API_DATA = { id: taskId };
			if (_id && (typeof _id === "string" || typeof _id === "number")) {
				API_DATA.id = _id;
			}
			downLoadFile(API_DATA).then(res => {
				console.log("任务下载，完成", res);

				const { data, msg: msg1, message: msg2 } = res;
				if (data && typeof data === "string" && String(data).startsWith("http")) {
					setStep(pre => ({ ...pre, third: true }));
					window.open(data);
				} else {
					message.error(msg1 || msg2 || "下载文件失败");
					setStep(pre => ({ ...pre, third: false }));
				}
			});
		},
		[taskId]
	);

	const startTask = useCallback(
		(params, callback) => {
			console.log("任务创建，开始");
			createImportTask(params).then(({ success, data: tid, msg: msg1, message: msg2 }) => {
				setTaskId(tid);

				if (success) {
					console.log("任务创建，完成");
					setStep(pre => ({ ...pre, first: true }));

					setTimer(
						getImportTaskRate,
						{ taskId: tid },
						({ success, completed, importedNum, taskId, totalNum, successNum, failNum }) => {
							if (success === false) {
								setStep(pre => ({ ...pre, second: false }));
								return false;
							}
							if (completed) {
								console.log("任务导入，完成 tid", tid);

								setStep(pre => ({ ...pre, second: true }));

								setResult({ completed, importedNum, taskId, totalNum, successNum, failNum });

								callback && callback(tid);

								return true;
							} else {
								console.log("任务导入，进行中");
								console.log("setPercent");
								setPercent((((importedNum || 0) / (totalNum || 1)) * 100).toFixed());
								return false;
							}
						}
					);
				} else {
					setStep(pre => ({ ...pre, first: false }));
					message.warning(msg1 || msg2 || "任务创建失败");
				}
			});
		},
		[setTaskId]
	);

	/**
	 * 完整的下载步骤
	 * 创建任务，轮询进度，下载文件
	 * @param {*} params 导入参数
	 */
	const downloadTask = useCallback(
		params => {
			startTask(params, tid => handleDownload(tid));
		},
		[startTask, handleDownload]
	);

	return {
		taskId, //导入任务id
		percent, // 导入进度
		result, // 导入结果
		setTimer, // 轮询任务
		clearTimer, //  取消轮询任务
		step, // 任务步骤
		handleDownload, // 下载文件
		startTask, // 开始任务 (需要手动调用handleDownload下载)
		downloadTask, // 开始任务(完整的下载步骤)
		downloadImportTask: downloadTask
	};
};
